package com.sofwin.controller;

import com.google.code.kaptcha.Producer;
import com.sofwin.Constants;
import com.sofwin.dto.SResourceDto;
import com.sofwin.pojo.SUser;
import com.sofwin.service.SResourceService;
import com.sofwin.service.SUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private SUserService userService;
    @Autowired
    private SResourceService resourceService;
    @Autowired
    private Producer captchaProducer;

    @RequestMapping("toIndex")
    public String toIndex(HttpSession session, Model model){
        // 从session中获取当前对象
        SUser user = (SUser) session.getAttribute(Constants.CURR_USER);
        // 将角色的roleId传递
        List<SResourceDto> leftnav =  resourceService.selectRoleResource(user.getRoleId());
        model.addAttribute("leftnav",leftnav);
        return "index";
    }

    @PostMapping("login")
    public String login(SUser user, String code, HttpSession session){
        // 如果验证码为空，不行
        if (code==null){
            return "redirect:login.jsp";
        }
        // 获取code尾巴上的session
        String oldCode = session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY).toString();
        if (!code.equals(oldCode)){
            return "redirect:login.jsp";
        }
        /*// 是否有这号人
        boolean isExist = userService.checkLogin(user);
        if (isExist){
            // 进入数据库查询，获取该用户的所有信息
            user = userService.selectUser(user);
            session.setAttribute(Constants.CURR_USER,user);
            return "redirect:toIndex";
        }else {
            return "redirect:login.jsp";
        }*/
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginAccount(),user.getPwd());
        try {
            subject.login(token);
        }catch (UnknownAccountException ex){
            // 用户名不存在
            return "redirect:toIndex";
        }catch (IncorrectCredentialsException ex){
            // 密码不正确
            return "redirect:toIndex";
        }
        // 进入数据库查询，获取该用户的所有信息
        user = userService.selectUser(user);
        session.setAttribute(Constants.CURR_USER,user);
        return "redirect:toIndex";

    }
    @GetMapping("logout")
    public String loginOut(HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        session.invalidate();
        return "redirect:login.jsp";
    }
    @RequestMapping(value = "verification", method = RequestMethod.GET)
    public ModelAndView verification(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        // create the text for the image
        String capText = captchaProducer.createText();
        // store the text in the session
        request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }
}
